package com.neusoft.neuiotms.dcam.fixed.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.common.model.Dictionary;
import com.neusoft.neuiotms.common.model.DictionaryType;
import com.neusoft.neuiotms.common.repository.DictionaryRepository;
import com.neusoft.neuiotms.common.repository.DictionaryTypeRepository;
import com.neusoft.neuiotms.dcam.common.model.QLocation;
import com.neusoft.neuiotms.dcam.common.model.QManufacturer;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.model.AssetLifeCycle;
import com.neusoft.neuiotms.dcam.fixed.model.QAssetLifeCycle;
import com.neusoft.neuiotms.dcam.fixed.model.QAssetType;
import com.neusoft.neuiotms.dcam.fixed.model.QContract;
import com.neusoft.neuiotms.dcam.fixed.model.QMaintenance;
import com.neusoft.neuiotms.dcam.fixed.model.QProduct;
import com.neusoft.neuiotms.dcam.fixed.repository.CustomizedAssetLifeCycleRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.JPAExpressions;
import com.querydsl.jpa.JPQLQuery;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedAssetLifeCycleRepositoryImpl extends AbstractRepository
        implements CustomizedAssetLifeCycleRepository {
    @Autowired
    private DictionaryRepository dictionaryRepository;
    @Autowired
    private DictionaryTypeRepository dictionaryTypeRepository;

    @Override
    public List<AssetLifeCycle> search(final Searchable searchable) {
        final QAssetLifeCycle qAssetLifeCycle = QAssetLifeCycle.assetLifeCycle;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<AssetLifeCycle> query = this.query().selectFrom(qAssetLifeCycle);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Long count(final Searchable searchable) {
        final QAssetLifeCycle qAssetLifeCycle = QAssetLifeCycle.assetLifeCycle;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<AssetLifeCycle> query = this.query().selectFrom(qAssetLifeCycle);
        query.where(where);
        return query.fetchCount();
    }

    @Override
    public Page<AssetLifeCycle> search(final Pageable pageable, final Searchable searchable) {
        final QAssetLifeCycle qAssetLifeCycle = QAssetLifeCycle.assetLifeCycle;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<AssetLifeCycle> query = this.query().selectFrom(qAssetLifeCycle);
        query.where(where);
        return super.search(query, pageable);
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QAssetLifeCycle qAssetLifeCycle = QAssetLifeCycle.assetLifeCycle;

        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.and(super.containsStr(qAssetLifeCycle.name, searchable, "name"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("code"))) {
            where.and(super.containsStr(qAssetLifeCycle.code, searchable, "code"));
        }
        // 资产codes集合
        final String[] codes = searchable.getStrArray("codes");
        if ((codes != null) && (codes.length > 0)) {
            where.and(super.inStrings(qAssetLifeCycle.code, searchable, "codes"));
        }

        // 类型ID集合
        final String[] assetTypeCodes = searchable.getStrArray("assetTypeCodes");
        if ((assetTypeCodes != null) && (assetTypeCodes.length > 0)) {
            where.and(super.inStrings(qAssetLifeCycle.type.code, searchable, "assetTypeCodes"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("assetTypeId"))) {
            where.and(super.equalsLong(qAssetLifeCycle.type.id, searchable, "assetTypeId"));//类型code
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("assetTypeCode"))) {
            where.and(super.equalsStr(qAssetLifeCycle.type.code, searchable, "assetTypeCode"));//类型code
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("useDept"))) {
            where.and(super.containsStr(qAssetLifeCycle.useDept, searchable, "useDept"));
        }
        final String[] submmitTo = searchable.getStrArray("submmitTo");
        if ((submmitTo != null) && (submmitTo.length > 0)) {
            where.and(super.inStrings(qAssetLifeCycle.submmitTo, searchable, "submmitTo"));
        } else {
            where.and(super.inStrings(qAssetLifeCycle.belongTo, searchable, "-all"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("statusCode"))) {
            where.and(
                    super.equalsStr(qAssetLifeCycle.status, searchable, "statusCode"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("assetSource"))) {
            where.and(
                    super.equalsStr(qAssetLifeCycle.source, searchable, "assetSource"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("sequence"))) {
            where.and(super.containsStr(qAssetLifeCycle.sequence, searchable, "sequence"));
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("money"))) {
            where.and(super.operateDouble(qAssetLifeCycle.money, searchable, "money"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("month"))) {
            where.and(super.equalsDouble(qAssetLifeCycle.month, searchable, "month"));
        }
        if (!StringUtils.isEmpty(searchable.getStrValue("submitTo"))) {
            where.and(super.containsStr(qAssetLifeCycle.submmitTo, searchable, "submitTo"));
        }
        if (null != searchable.getLongValue("start")) {
            where.and(super.afterOrEqualsDate(qAssetLifeCycle.usedate, searchable, "start"));
        }

        if (null != searchable.getLongValue("end")) {
            where.and(super.beforeOrEqualsDate(qAssetLifeCycle.usedate, searchable, "end"));
        }

        if (null != searchable.getLongValue("manufacturerEndDateStart")) {
            where.and(super.afterOrEqualsDate(qAssetLifeCycle.manufacturerEndDate, searchable,
                    "manufacturerEndDateStart"));
        }

        if (null != searchable.getLongValue("manufacturerEndDateEnd")) {
            where.and(super.beforeOrEqualsDate(qAssetLifeCycle.manufacturerEndDate, searchable,
                    "manufacturerEndDateEnd"));
        }

        if (searchable.hasKey("statusCodeIn")) {
            where.and(
                    super.inStrings(qAssetLifeCycle.status, searchable, "statusCodeIn"));
        }

        if (!StringUtils.isEmpty(searchable.getStrValue("globalSearch"))) {
            final BooleanBuilder whereGlobal = new BooleanBuilder();
            final DictionaryType dictionaryType = this.dictionaryTypeRepository.findByType(DCAMConsts.ASSET_SOURCE);
            final List<Dictionary> source =
                    this.dictionaryRepository.findByDictionaryTypeOrderBySortAsc(dictionaryType);
            for (int i = 0; i < source.size(); i++) {
                if (source.get(i).getText().contains(searchable.getStrValue("globalSearch"))) {
                    searchable.put("source" + i, source.get(i).getCode());
                    whereGlobal.or(super.containsStr(qAssetLifeCycle.source, searchable, "source" + i));
                }
            }
            final DictionaryType dictionaryTypeStatus =
                    this.dictionaryTypeRepository.findByType(DCAMConsts.ASSET_STATUS);
            final List<Dictionary> status =
                    this.dictionaryRepository.findByDictionaryTypeOrderBySortAsc(dictionaryTypeStatus);
            for (int i = 0; i < status.size(); i++) {
                if (status.get(i).getText().contains(searchable.getStrValue("globalSearch"))) {
                    searchable.put("status" + i, status.get(i).getCode());
                    whereGlobal.or(super.containsStr(qAssetLifeCycle.status, searchable, "status" + i));
                }
            }

            whereGlobal.or(super.containsStr(qAssetLifeCycle.userName, searchable, "globalSearch"));
            whereGlobal.or(super.containsStr(qAssetLifeCycle.sequence, searchable, "globalSearch"));
            whereGlobal.or(super.containsStr(qAssetLifeCycle.code, searchable, "globalSearch"));
            whereGlobal.or(super.containsStr(qAssetLifeCycle.name, searchable, "globalSearch"));

            final QMaintenance qMaintenance = QMaintenance.maintenance;
            final QAssetType qAssetType = QAssetType.assetType;
            final QContract qContract = QContract.contract;
            final QProduct qProduct = QProduct.product;
            final QLocation qLocation = QLocation.location;
            final QManufacturer qManufacturer = QManufacturer.manufacturer;

            final JPQLQuery<Long> reQuery = JPAExpressions.select(qAssetLifeCycle.id).from(qAssetLifeCycle)
                    .leftJoin(qAssetType).on(qAssetLifeCycle.type.id.eq(qAssetType.id));

            final BooleanBuilder likeWhere =
                    new BooleanBuilder()
                            .or(super.containsStr(qMaintenance.maintenanceNote, searchable, "globalSearch"))
                            .or(super.containsStr(qMaintenance.maintenanceUserName, searchable, "globalSearch"))
                            .or(super.containsStr(qMaintenance.maintenanceNote, searchable, "globalSearch"))
                            .or(super.containsStr(qAssetType.name, searchable, "globalSearch"))
                            .or(super.containsStr(qContract.name, searchable, "globalSearch"))
                            .or(super.containsStr(qProduct.name, searchable, "globalSearch"))
                            .or(super.containsStr(qLocation.name, searchable, "globalSearch"))
                            .or(super.containsStr(qAssetLifeCycle.submmitTo, searchable, "globalSearch"))
                            .or(super.containsStr(qManufacturer.name, searchable, "globalSearch"));

            reQuery.where(likeWhere);

            whereGlobal.or(qAssetLifeCycle.id.in(reQuery));
            where.and(whereGlobal);

        }
        return where;
    }

    @Override
    protected Class<?> getModelClass() {
        return AssetLifeCycle.class;
    }

}
